import { useEffect, useState, useRef, useContext } from 'react'
import { Skeleton } from 'antd'
import { SelectEntry as Select } from '@/pages/bi-core/components/DataEntry/ValueEntry'
import { ApiContext } from '@/api/ApiHub'
import FieldList from './FieldList'
import styles from './index.module.less'

const DataField = ({ value: datasetId, onChange }) => {
  const api = useContext(ApiContext)

  const isMore = useRef(true)
  const pageNum = useRef(1)
  const selectLoading = useRef(false)
  const [loading, setLoading] = useState(false)
  const [datasets, setDatasets] = useState([])
  const [dmFields, setDmFields] = useState([])

  useEffect(() => {
    getDatasets()
  }, [])

  const getDatasets = async () => {
    selectLoading.current = true
    const { data, totalPage } = await api.getDatasetsForDashboard({
      pageSize: 200,
      ids: ['1696087152263280'],
      dynamicParams: {},
      extensionParams: {
        "dashboardId": "1696087152263280",
        "districtId": "1379528330444805",
        "dynamicParams": {}
      }
    })
    const id = datasetId ?? data[0]?.id
    getDatasetInfo(id)
    setDatasets([...datasets, ...data])
    isMore.current = pageNum.current < totalPage
    selectLoading.current = false
  }

  const getDatasetInfo = async (id) => {
    setLoading(true)
    const { fields } = await api.getDataset(id)
    parseDmFields(fields)
    onChange(id)
    setLoading(false)
  }

  const parseDmFields = (fields) => {
    const dmKey = {
      dimension: '维度',
      measure: '度量'
    }
    const dmFields = Object.entries(dmKey).map(([key, title]) => ({
      key,
      title,
      fields: fields.filter((item) => item.fieldClassify === key)
    }))
    setDmFields(dmFields)
  }

  const onPopupScroll = (e) => {
    if (!isMore.current) return
    const { clientHeight, scrollHeight, scrollTop } = e.target
    if (scrollHeight - scrollTop > clientHeight && !selectLoading.current) {
      pageNum.current += 1
      getDatasets()
    }
  }

  return (
    <div className={styles['data-field']}>
      <div className={styles['data-select']}>
        <label>数据集</label>
        <Select
          options={datasets.map((v) => ({ label: v.name, value: v.id }))}
          value={datasetId}
          onChange={getDatasetInfo}
          onPopupScroll={onPopupScroll}
          showSearch
          size="middle"
          optionFilterProp="children"
          dropdownClassName="bi-core-dropdown"
        />
      </div>
      <div className={styles['field-select']}>
        {loading ? (
          <Skeleton />
        ) : (
          <>
            {dmFields.map((dm) => (
              <FieldList key={dm.key} dmField={dm} />
            ))}
          </>
        )}
      </div>
    </div>
  )
}

export default DataField
